package com.example.demo.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileUrlResource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.jms.BytesMessage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Rocket
 * @version 10.1.0
 * @date 2021-10-11 5:33 PM
 */
@Component
public class WsLogHandler extends TextWebSocketHandler {
    List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //Map<String, Object> value = objectMapper.readValue(message.getPayload(), Map.class);
        System.out.println("Message from client: " + message.toString());
        for(;;) {
            Thread.sleep(1000);
            session.sendMessage(new TextMessage("Hello World !" + new Date()));
            //session.sendMessage();
        }

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("add session: " + session.getId());
        File file = ResourceUtils.getFile("classpath:wechat.jpg");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        FileUtils.copyFile(file, bos);
        BinaryMessage  binaryMessage = new BinaryMessage(bos.toByteArray());
        session.sendMessage(binaryMessage);
        sessions.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("remove session: " + session.getId());
        sessions.remove(session);
    }
}
